﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UIFade : MonoBehaviour
{
    public bool _opening;
    public bool _closing;

    public float fadeTime = 1.0f;
    private float timer;

    void Start()
    {
        // 初始时_opening设为true，实现打开时淡入效果
        _opening = true;
        _closing = false;
        timer = 0;
        // alpha设为0，为全透明
        gameObject.transform.GetComponent<CanvasGroup>().alpha = 0;
    }

    // Update is called once per frame
    void Update()
    {
        //Debug.Log("close: " + _closing);
        //Debug.Log("open: " + _opening);
        // 处于打开状态，alpha随时间增加
        if (_opening == true)
        {
            // 找到Panel的alpha的值，随时间增加，实现淡入效果
            gameObject.transform.GetComponent<CanvasGroup>().alpha += Time.unscaledDeltaTime * 3f;

            // 当alpha>=1时，打开状态结束，_opening设置false
            if (gameObject.transform.GetComponent<CanvasGroup>().alpha >= 1)
                _opening = false;
        }
        else
        {
            timer += Time.unscaledDeltaTime;
            if(timer> fadeTime)
            {
                _closing = true;
            }
        }

        if (_closing == true)
        {
            // 处于关闭状态，alpha随时间减少
            gameObject.transform.GetComponent<CanvasGroup>().alpha -= Time.unscaledDeltaTime * 3f;

            // alpha小于0，关闭状态结束，_closing设为false，并且在UI Root下删除该Panel
            if (gameObject.transform.GetComponent<CanvasGroup>().alpha <= 0)
            {
                _closing = false;
                Destroy(gameObject);
            }
        }
    }
}